package android.demo.engine.tasks;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.demo.engine.ProcessStateManager;
import android.demo.engine.RootActivity;
import android.os.IBinder;
import android.widget.Toast;

/**
 * @author  carlo
 */
public class ServiceBinderTask extends ServiceTask {

	/**
	 * @uml.property  name="flags"
	 */
	private int flags;
	private ServiceConnection connection;
	
	public ServiceBinderTask(int id) {
		super(id);
		flags= Service.BIND_AUTO_CREATE;
	}

	@Override
	public short getType() {
		return Task.Types.SERVICE_BINDER_TASK;
	}
	
	@Override
	public void init() {
		super.init();
		this.connection=null;
	}
	/**
	 * @return
	 * @uml.property  name="flags"
	 */
	public int getFlags() {
		return flags;
	}

	public ServiceConnection getConnection(Activity rootAct) {
		if(connection==null)
			createConnection(rootAct);
		return connection;
	}

	public void dialogueWith(IBinder service) {
		//TODO call some method from service
//		try{
//			service.getClass().getMethod("",null).invoke(service,null);
//		}catch(Exception e){}
	}
	private void createConnection(final Activity rootAct) {
		connection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO service killed
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			dialogueWith(service);
			rootAct.unbindService(this);
			finish();
		}

};
	}
	@Override
	public void finish() {
		connection=null;
		super.finish();
	}
	


}
